package com.health;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import com.google.gson.Gson;
import com.health.adapter.DownloadGridViewAdapter;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tablebean.CD_DIABETESFOLLOWUP;
import com.health.tablebean.CD_DRUGCONDITION;
import com.health.tablebean.CD_HYPERTENSIONFOLLOWUP;
import com.health.tablebean.PharmacyList;
import com.health.tablebean.webservice.Diabetes;
import com.health.tablebean.webservice.Hypertensio;
import com.health.tablebean.webservice.Rollout;
import com.health.tools.GlobalConts;
import com.health.tools.ResultTextDialog;
import com.health.tools.WebService;
import com.health.webservices.WebServiceConts;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class DataDownLoadActivity extends NovaActivity implements AdapterView.OnItemClickListener {

    private String TAG = "DataDownLoadActivity";
    private GridView gv;
    private DownloadGridViewAdapter adapter;
    private ResultTextDialog resultDialog;
    private ARCHIVE_BASEINFO userinfo = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userinfo = NovaApplication.getUserInfo();
        setContentView(R.layout.activity_data_down_load);
        findViews();
        setListeners();
    }

    @Override
    public void findViews() {
        gv = (GridView) findViewById(R.id.gv);
        adapter = new DownloadGridViewAdapter(DataDownLoadActivity.this);
        gv.setAdapter(adapter);
    }

    @Override
    public void setListeners() {
        gv.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (!GlobalConts.isNetworkAvailable(DataDownLoadActivity.this)) {
            showTextDialog("请先检查网络");
            return;
        }
        if (resultDialog == null) {
            resultDialog = new ResultTextDialog(DataDownLoadActivity.this);
        }

        resultDialog.show("数据校验中，请稍候...");
        if (position == 0) {
            //高血压数据下载
            downLoadGXY();
        } else if (position == 1) {
            //糖尿病数据下载
            downLoadTNB();
        }
    }

    /**
     * 高血压数据下载
     */
    private void downLoadGXY() {
        try {
            WebService webService = new WebService(this) {


                @Override
                public void complete(String message) {
                    super.complete(message);
                    dataAnalysis_GXY(message);
                    Log.e(TAG, "complete" + message);
                }

                @Override
                public void onError(String message) {
                    super.onError(message);
                    setDialogText("数据下载失败");
                    resultDialog.showCancleLong();
                }
            };

            HashMap<String, Object> params = new HashMap<String, Object>();
            params.put("cardid", userinfo.getIDCARD());

            webService.downloaddata(GlobalConts.getUrlPost() + WebServiceConts.WEBSERVICE_URL_GXY,
                    WebServiceConts.WEBSERVICE_URL_GXY_METHODNAME, WebServiceConts.WEBSERVICE_URL_XZQ_NAMESPACE,
                    null, params, "getGxyByCardid");
        } catch (Exception e) {
            e.printStackTrace();
            setDialogText("数据下载失败");
            resultDialog.showCancleLong();
        }
    }

    private void setDialogText(final String str) {
        runOnUiThread(new Runnable() {
            public void run() {
                resultDialog.setText(str);
            }
        });
    }

    /**
     * 高血压数据解析
     *
     * @param message
     */
    private void dataAnalysis_GXY(String message) {
        try {
            JSONArray jsonArray = new JSONArray(message.toString());
            if (jsonArray.length() > 0) {
                JSONObject object = (JSONObject) jsonArray.get(0);
                String state = object.getString("state");
                if ("000".equals(state)) {
                    JSONObject data = object.getJSONObject("data");
                    Gson gson = new Gson();
                    Hypertensio hypertensio = gson.fromJson(data.toString(), Hypertensio.class);
                    CD_HYPERTENSIONFOLLOWUP gxy = new CD_HYPERTENSIONFOLLOWUP();
                    gxy.setWEIGHT(hypertensio.getAvoirdupois());
                    gxy.setIDCARD(hypertensio.getCardid());
                    gxy.setOBEYDOCTORBEHAVIOR(hypertensio.getCompiance());
                    gxy.setCREATEORG(hypertensio.getCreateorg());
                    gxy.setCREATEORG(hypertensio.getCreater());
                    gxy.setSYMPTOM(hypertensio.getCurSymptom());
                    gxy.setMEDICATIONCOMPLIANCE(hypertensio.getDependence());
                    gxy.setDAILYDRINKNUM(hypertensio.getDrink());
                    gxy.setADR_EX(hypertensio.getEffectsState());
                    try {
                        if (!TextUtils.isEmpty(hypertensio.getHappentime())) {
                            gxy.setFOLLOWUPDATE(GlobalConts.dateFormat.parse(hypertensio.getHappentime()));
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    gxy.setFOLLOWUPDOCTOR(hypertensio.getInputMan());
                    gxy.setPSYCHOADJUSTMENT(hypertensio.getMentality());
                    try {
                        if (!TextUtils.isEmpty(hypertensio.getNextVisitDate())) {
                            gxy.setNEXTFOLLOWUPDATE(GlobalConts.dateFormat.parse(hypertensio.getNextVisitDate()));
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    gxy.setPHYSICALSYMPTOMOTHER(hypertensio.getOtherPositive());
                    gxy.setSYMPTOMOTHER(hypertensio.getOtherSymptom());
                    gxy.setARCHIVEID(hypertensio.getPersonalid());
                    gxy.setBMI(hypertensio.getPhysique());
                    gxy.setHYPERTENSION(hypertensio.getPressureH());
                    gxy.setHYPOTENSION(hypertensio.getPressureL());
                    gxy.setHEARTRATE(hypertensio.getPulseRate());
                    gxy.setDAILYDRINKNUMTARGET(hypertensio.getTargetDrink());
                    Rollout rollout = hypertensio.getRollout();
                    if (rollout != null) {
                        gxy.setREFERRALREASON(TextUtils.isEmpty(rollout.getHpc()) ? "" : rollout.getHpc());
                        gxy.setREFERRALORG(TextUtils.isEmpty(rollout.getRollInRegion()) ? "" : rollout.getRollInRegion());
                    }
                    gxy.setEATSALTTYPE(hypertensio.getSalt());
                    gxy.setADR(hypertensio.getSideEffects());
                    gxy.setDAILYSMOKENUM(hypertensio.getSmoke());
                    gxy.setASSISTANTEXAM(hypertensio.getSubCheck());
                    gxy.setWEIGHTTARGET(hypertensio.getTargetAvoirdupois());
                    gxy.setBMITARGET(hypertensio.getTargetPhysique());
                    gxy.setEATSALTTARGET(hypertensio.getTargetSalt());
                    gxy.setDAILYSMOKENUMTARGET(hypertensio.getTargetSmoke());
                    gxy.setSPORTTIMESPERWEEKTARGET(hypertensio.getTargetTraining());
                    gxy.setSPORTPERMINUTESTIMETARGET(hypertensio.getTargetTrainingMin());
                    gxy.setSPORTTIMEPERWEEK(hypertensio.getTraining());
                    gxy.setSPORTPERMINUTETIME(hypertensio.getTrainingMin());
                    gxy.setFOLLOWUPTYPE(hypertensio.getVisitType());
                    if (hypertensio.getVisitWay().contains("DM04-04")){
                        Log.e("随诊方式1",hypertensio.getVisitWay());
                        gxy.setFOLLOWUPWAY(hypertensio.getVisitWay().replace("DM04-04","DM04-15"));
                    }else{
                        gxy.setFOLLOWUPWAY(hypertensio.getVisitWay());
                        Log.e("随诊方式2",hypertensio.getVisitWay());
                    }


                    gxy.setHeight("");

                    List<CD_HYPERTENSIONFOLLOWUP> gxyList = NovaApplication.fdbmanger.findAllByWhere(CD_HYPERTENSIONFOLLOWUP.class,
                            "IDCARD = '" + userinfo.getIDCARD() + "'");

                    if (gxyList.size() > 0) {
                        CD_HYPERTENSIONFOLLOWUP hypertensionfollowup = gxyList.get(0);
                        Date created_date_local = hypertensionfollowup.getCREATED_DATE();
                        Date last_update_date = hypertensionfollowup.getLAST_UPDATE_DATE();

                        //修改时间为空，未作修改，通过创建时间进行判断
                        if (TextUtils.isEmpty(hypertensio.getUpdatetime())) {
                            //本地修改时间大于服务器创建时间， 不需要修改本地高血压随访数据
                            if (!TextUtils.isEmpty(hypertensio.getCreatetime())) {
                                if (compare_date(last_update_date, hypertensio.getCreatetime())) {
                                    setDialogText("已经是最新数据，无需下载");
                                    resultDialog.showCancleLong();
                                    return;
                                } else {
                                    //本地创建时间小于服务器创建时间，修改本地高血压随访数据，并且删除本人的所有药物数据重新存储
                                    deleteOldDrugData();
                                    List<PharmacyList> pharmacyList = hypertensio.getPharmacyList();
                                    saveDrug(pharmacyList, "1");
                                    NovaApplication.fdbmanger.updata(gxy, "IDCARD='" + userinfo.getIDCARD() + "'");
                                }
                            }

                        } else {
                            //修改时间不为空，已经修改，通过修改时间进行判断（代码确定本地修改时间一定存在）
                            if (compare_date(last_update_date, hypertensio.getUpdatetime())) {
                                //本地修改时间大于服务器修改时间， 不需要修改本地高血压随访数据
                                setDialogText("已经是最新数据，无需下载");
                                resultDialog.showCancleLong();
                                return;
                            } else {
                                //本地修改时间小于服务器修改时间， 修改本地高血压随访数据，并且删除本人的所有药物数据重新存储
                                deleteOldDrugData();
                                List<PharmacyList> pharmacyList = hypertensio.getPharmacyList();
                                saveDrug(pharmacyList, "1");
                                NovaApplication.fdbmanger.updata(gxy, "IDCARD='" + userinfo.getIDCARD() + "'");
                            }
                        }
                    } else {
                        //没有此人的数据直接进行保存
                        deleteOldDrugData();
                        List<PharmacyList> pharmacyList = hypertensio.getPharmacyList();
                        saveDrug(pharmacyList, "1");
                        NovaApplication.fdbmanger.save(gxy);
                    }
                    setDialogText("数据下载成功");
                    resultDialog.showCancleLong();
                }else if ("001".equals(state)){
                    setDialogText("无此人信息");
                    resultDialog.showCancleLong();
                }else if ("002".equals(state)){
                    setDialogText("此人非高血压患者");
                    resultDialog.showCancleLong();
                }else if ("009".equals(state)){
                    setDialogText("无此人随访数据");
                    resultDialog.showCancleLong();
                }
            } else {
                setDialogText("数据下载失败");
                resultDialog.showCancleLong();
            }

        } catch (JSONException e) {
            e.printStackTrace();
            setDialogText("数据下载失败");
            resultDialog.showCancleLong();
        }
    }


    /**
     * 糖尿病数据下载
     */
    private void downLoadTNB() {

        try {
            WebService webService = new WebService(this) {


                @Override
                public void complete(String message) {
                    super.complete(message);
                    dataAnalysis_TNB(message);
                    Log.e(TAG, "complete" + message);
                }

                @Override
                public void onError(String message) {
                    super.onError(message);
                    setDialogText("数据下载失败");
                    resultDialog.showCancleLong();
                }
            };

            HashMap<String, Object> params = new HashMap<String, Object>();
            params.put("cardid", userinfo.getIDCARD());

            webService.downloaddata(GlobalConts.getUrlPost() + WebServiceConts.WEBSERVICE_URL_TNB,
                    WebServiceConts.WEBSERVICE_URL_TNB_METHODNAME, WebServiceConts.WEBSERVICE_URL_XZQ_NAMESPACE,
                    null, params, "getTnbByCardid");
        } catch (Exception e) {
            e.printStackTrace();
            setDialogText("数据下载失败");
            resultDialog.showCancleLong();
        }

    }


    /**
     * 糖尿病数据解析
     *
     * @param message
     */
    private void dataAnalysis_TNB(String message) {
        try {
            JSONArray jsonArray = new JSONArray(message.toString());
            if (jsonArray.length() > 0) {
                JSONObject object = (JSONObject) jsonArray.get(0);
                String state = object.getString("state");
                if ("000".equals(state)) {
                    JSONObject data = object.getJSONObject("data");
                    Gson gson = new Gson();
                    Diabetes diabetes = gson.fromJson(data.toString(), Diabetes.class);
                    CD_DIABETESFOLLOWUP tnb = new CD_DIABETESFOLLOWUP();
                    tnb.setDORSALISPEDISPULSE(diabetes.getArteriopalmus());
                    tnb.setWEIGHT(diabetes.getAvoirdupois());
                    tnb.setIDCARD(diabetes.getCardid());
                    tnb.setOBEYDOCTORBEHAVIOR(diabetes.getCompiance());
                    tnb.setCREATEORG(diabetes.getCreateorg());
                    tnb.setCREATER(diabetes.getCreater());
                    try {
                        if (!TextUtils.isEmpty(diabetes.getHappentime())) {
                            tnb.setFOLLOWUP_DATE(GlobalConts.dateFormat.parse(diabetes.getHappentime()));
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    tnb.setMEDICATIONCOMPLIANCE(diabetes.getDependence());
                    tnb.setDAILYDRINKNUM(diabetes.getDrink());
                    tnb.setADR(diabetes.getSideEffects());
                    tnb.setADR_EX(diabetes.getEffectsState());
                    tnb.setFPG(diabetes.getFbg());
                    tnb.setHBALC(diabetes.getHgb());
                    tnb.setFOLLOWUPDOCTOR(diabetes.getInputMan());
                    tnb.setINSULINUSAGE(diabetes.getInsulinDose());
                    tnb.setINSULINTYPE(diabetes.getInsulinType());
                    tnb.setHYPOGLYCEMIARREACTION(diabetes.getLowEffects());
                    tnb.setPSYCHOADJUSTMENT(diabetes.getMentality());
                    try {
                        if (!TextUtils.isEmpty(diabetes.getNextVisitDate())) {
                            tnb.setNEXTFOLLOWUP_DATE(GlobalConts.dateFormat.parse(diabetes.getNextVisitDate()));
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    tnb.setPHYSICALSYMPTOMOTHER(diabetes.getOtherPositive());
                    tnb.setSYMPTOMOTHER(diabetes.getOtherSymptom());
                    tnb.setSYMPTOM(diabetes.getCurSymptom());
                    tnb.setBMI(diabetes.getPhysique());
                    tnb.setHYPERTENSION(diabetes.getPressureH());
                    tnb.setHYPOTENSION(diabetes.getPressureL());
                    if (!TextUtils.isEmpty(diabetes.getRes2())){
                        if (!TextUtils.isEmpty(diabetes.getHappentime())){
                            String[] split = diabetes.getHappentime().split("-");
                            try {
                                tnb.setEXAMDATE(GlobalConts.dateFormat.parse(split[0] + "-"+diabetes.getRes2() + "-" + diabetes.getRes3()));
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    tnb.setDORSALISPEDISPULSE_Less(diabetes.getRes5());
                    tnb.setDORSALISPEDISPULSE_Disa(diabetes.getRes6());
                    tnb.setSTAPLEFOODDAILYG(diabetes.getRice());
                    tnb.setDAILYSMOKENUM(diabetes.getSmoke());
                    tnb.setASSISTANTEXAM(diabetes.getSubCheck());
                    tnb.setWEIGHTTARGET(diabetes.getTargetAvoirdupois());
                    tnb.setDAILYDRINKNUMTARGET(diabetes.getTargetDrink());
                    tnb.setBMITARGET(diabetes.getTargetPhysique());
                    tnb.setSTAPLEFOODDAILYGTARGET(diabetes.getTargetRice());
                    tnb.setDAILYSMOKENUMTARGET(diabetes.getTargetSmoke());
                    tnb.setSPORTTIMESPERWEEKTARGET(diabetes.getTargetTraining());
                    tnb.setSPORTPERMINUTESTIMETARGET(diabetes.getTargetTrainingMin());
                    tnb.setSPORTTIMEPERWEEK(diabetes.getTraining());
                    tnb.setSPORTPERMINUTETIME(diabetes.getTrainingMin());
                    tnb.setFOLLOWUPTYPE(diabetes.getVisitType());
                    if (diabetes.getVisitWay().contains("DM04-04")){
                        tnb.setFOLLOWUPWAY(diabetes.getVisitWay().replace("DM04-04","DM04-15"));
                    }else{
                        tnb.setFOLLOWUPWAY(diabetes.getVisitWay());
                    }

                    try {
                        if (!TextUtils.isEmpty(diabetes.getUpdatetime())) {
                            tnb.setLAST_UPDATE_DATE(GlobalConts.dateFormat.parse(diabetes.getUpdatetime()));
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    Diabetes.Rolloutrollout rollout = diabetes.getRollout();
                    if (rollout != null) {
                        tnb.setREFERRALREASON(TextUtils.isEmpty(rollout.getHpc()) ? "" : rollout.getHpc());
                        tnb.setREFERRALORG(TextUtils.isEmpty(rollout.getRollInRegion()) ? "" : rollout.getRollInRegion());
                    }


                    List<CD_DIABETESFOLLOWUP> tnbList = NovaApplication.fdbmanger.findAllByWhere(CD_DIABETESFOLLOWUP.class,
                            "IDCARD = '" + userinfo.getIDCARD() + "'");

                    if (tnbList.size() > 0) {
                        CD_DIABETESFOLLOWUP diabetesfollowup = tnbList.get(0);
                        Date created_date_local = diabetesfollowup.getCREATED_DATE();
                        Date last_update_date = diabetesfollowup.getLAST_UPDATE_DATE();

                        //修改时间为空，未作修改，通过创建时间进行判断
                        if (TextUtils.isEmpty(diabetes.getUpdatetime())) {
                            //本地创建时间大于服务器创建时间， 不需要修改本地高血压随访数据
                            if (!TextUtils.isEmpty(diabetes.getCreatetime())) {
                                if (compare_date(created_date_local, diabetes.getCreatetime())) {
                                    setDialogText("已经是最新数据，无需下载");
                                    resultDialog.showCancleLong();
                                    return;
                                } else {
                                    //本地创建时间小于服务器创建时间，修改本地高血压随访数据，并且删除本人的所有药物数据重新存储
                                    deleteOldDrugData();
                                    List<PharmacyList> pharmacyList = diabetes.getPharmacyList();
                                    saveDrug(pharmacyList, "2");
                                    NovaApplication.fdbmanger.updata(tnb, "IDCARD='" + userinfo.getIDCARD() + "'");
                                }
                            }

                        } else {
                            //修改时间不为空，已经修改，通过修改时间进行判断（代码确定本地修改时间一定存在）
                            if (compare_date(last_update_date, diabetes.getUpdatetime())) {
                                //本地修改时间大于服务器修改时间， 不需要修改本地高血压随访数据
                                setDialogText("已经是最新数据，无需下载");
                                resultDialog.showCancleLong();
                                return;
                            } else {
                                //本地修改时间小于服务器修改时间， 修改本地高血压随访数据，并且删除本人的所有药物数据重新存储
                                deleteOldDrugData();
                                List<PharmacyList> pharmacyList = diabetes.getPharmacyList();
                                saveDrug(pharmacyList, "2");
                                NovaApplication.fdbmanger.updata(tnb, "IDCARD='" + userinfo.getIDCARD() + "'");
                            }
                        }
                    } else {
                        //没有此人的数据直接进行保存
                        deleteOldDrugData();
                        List<PharmacyList> pharmacyList = diabetes.getPharmacyList();
                        saveDrug(pharmacyList, "2");
                        NovaApplication.fdbmanger.save(tnb);
                    }
                    setDialogText("数据下载成功");
                    resultDialog.showCancleLong();
                }else if ("001".equals(state)){
                    setDialogText("无此人信息");
                    resultDialog.showCancleLong();
                }else if ("002".equals(state)){
                    setDialogText("此人非糖尿病患者");
                    resultDialog.showCancleLong();
                }else if ("009".equals(state)){
                    setDialogText("无此人随访数据");
                    resultDialog.showCancleLong();
                }
            }else{
                setDialogText("数据下载失败");
                resultDialog.showCancleLong();
            }

        } catch (JSONException e) {
            e.printStackTrace();
            setDialogText("数据下载失败");
            resultDialog.showCancleLong();
        }
    }


    /**
     * 比较两个时间的大小，dt1大于DATE2，返回true，否则返回false
     *
     * @param dt1
     * @param DATE2
     * @return
     */
    public boolean compare_date(Date dt1, String DATE2) {

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date dt2 = df.parse(DATE2);
            if (!(dt1.getTime() < dt2.getTime())) {
                return true;
            } else {
                return false;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }


    /**
     * 删除以前的药物数据
     */
    private void deleteOldDrugData() {
        List<CD_DRUGCONDITION> drugList = NovaApplication.fdbmanger.findAllByWhere(CD_DRUGCONDITION.class,
                "IDCARD = '" + NovaApplication.getUserInfo().getIDCARD() + "' and TYPE='1'");
        for (CD_DRUGCONDITION drug : drugList) {
            if (drug != null) {
                NovaApplication.fdbmanger.delete(drug);
            }
        }
    }

    /**
     * 保存药物数据
     *
     * @param pharmacyList
     */
    private void saveDrug(List<PharmacyList> pharmacyList, String type) {
        if (pharmacyList != null && pharmacyList.size() > 0) {
            for (PharmacyList list : pharmacyList) {
                CD_DRUGCONDITION drugcondition = new CD_DRUGCONDITION();
                drugcondition.setEVERYTIMEMG(list.getDosage());
                drugcondition.setNAME(list.getDrugName());
                drugcondition.setRES1(list.getReg2());
                drugcondition.setDAILYTIME(list.getUsage());
                drugcondition.setTYPE(type);
                drugcondition.setIDCARD(userinfo.getIDCARD());
                NovaApplication.fdbmanger.save(drugcondition);
            }
        }
    }


}
